myApp.filter('ucListFilter', [function () {
    return function (uclist) {
        var list = [];
        var userAccount = getUserAccount();

        if (isUserCanOperateByRole('ops', 'audit', 'assign', 'ucloud_admin')) {
            return uclist;
        }

        angular.forEach(uclist, function (uc) {
            if (ucIsIntegration(uc.ip) || arrayContains(c_ucloud_list, uc.ip)) {
                list.push(uc);
            } else {
                if (uc.applicant_id != null && uc.applicant_id == getUserId()) {
                    list.push(uc);
                } else if (uc.planInfo != null) {
                    if (uc.planInfo.PM == userAccount) {
                        list.push(uc);
                    } else {
                        var members = uc.planInfo.members;
                        angular.forEach(members, function (member) {
                            if (member.account == userAccount) {
                                list.push(uc);
                                return;
                            }
                        });
                    }
                }
            }
        });
        return list;
    };
}]);
myApp.filter('ucSearchFilter', [function () {
    return function (uclist, agentIp) {
        var list = [];
        angular.forEach(uclist, function (uc) {
            if (agentIp == '') {
                list.push(uc);
            } else if (typeof uc.ip != undefined && uc.ip.indexOf(agentIp) != -1) {
                list.push(uc);
            }
        });
        return list;
    };
}]);
myApp.controller('newuclistController', function ($scope, $uibModal, $stateParams, ngDialog, $filter, $http, $interval) {
    $scope.info = {};
    //搜索框默认值
    $scope.info.agent_ip = $stateParams.agent_ip;
    $scope.info.uclist = [];
    $scope.info.loadlist = [];
    $scope.info.userName = getUserName();
    $scope.info.userRole = getUserRole();
    $scope.total = $scope.info.uclist.length;
    $scope.page = {size: 15, index: 1};

    $scope.timer = null;
    $scope.$on("$destroy", function () {
        if ($scope.timer != null) {
            console.log("清除项目定时器;");
            $interval.cancel($scope.timer);
        }
    });

    $scope.arrayContains = function (array, obj) {
        return arrayContains(array, obj);
    };

    $scope.isCEnv = function (i) {
        return arrayContains(c_ucloud_list, i.ip);
    };

    $scope.agent_list = function () {
        $http.get(ucloud_master_url + '/api/v1/agent/?token_id=' + getTokenId()).success(function (data) {
            var list = data.data;
            var plans = '';
            for (var i in list) {
                if (list[i].plan_id == null || list[i].plan_id == '') {
                    continue
                }
                plans += list[i].plan_id + ',';
            }
            plans = plans.substring(0, plans.length - 1);
            $http.post(beetle_plan_url + '/project_plan/getPlanList', {
                token_id: getTokenId(),
                isShowOnline: true,
                plan_id: plans
            }).success(function (d) {
                angular.forEach(list, function (agent) {
                    if ((arrayContains(c_ucloud_list, agent.ip) && isUserCanOperateByRole($scope.info.userRole, 'c_admin')) || !arrayContains(c_ucloud_list, agent.ip)) {
                        agent.btnShow = true;
                    } else {
                        agent.btnShow = false;
                    }
                    agent.planInfo = null;
                    if (agent.plan_id != null && agent.plan_id != '') {
                        angular.forEach(d.data, function (plan) {
                            if (agent.plan_id == plan.plan_id) {
                                agent.planInfo = plan;
                                return;
                            }
                        })
                    }
                });
                $scope.info.uclist = $filter('ucListFilter')(list);
                $scope.getAutoStatusList();
                if ($scope.timer != null) {
                    $interval.cancel($scope.timer);
                }
                $scope.timer = $interval(function () {
                    //查询agent的冒烟测试状态
                    $scope.getAutoStatusList();
                }, 60000);

            });
        });
    };
    $scope.agent_list();

    $scope.getAutoStatusList = function () {
        angular.forEach($scope.info.uclist, function (agent) {
            $scope.getAutoStatus(agent);
        })
    };

    //根据ip获取冒烟测试状态
    $scope.getAutoStatus = function (agent) {
        var url = 'http://' + agent.ip + ':5000/api/v1/apps/testStatus';
        $http.get(url).success(function (data) {
            if (data.success == true) {
                agent.autoTestStatus = data.msg;
            }
        })
    };

    $scope.goToTestRestltHtml = function (agent) {
        window.open('http://' + agent.ip + ":1188");
    };

    $scope.godel = function (i) {
        openDialog(ngDialog, $scope, "确定要删除当前虚拟机吗?", true, function (val) {
            if (!val) {
                return;
            }
            $http.get(ucloud_master_url + '/api/v1/agent/del?token_id=' + getTokenId() + '&agent_id=' + i.id).success(function (data) {
                if (data.success == true) {
                    $scope.agent_list();
                } else {
                    alert(data.msg);
                }
            })
        });
    };

    $scope.goInitApp = function (agent) {
        openDialog(ngDialog, $scope, "请确认是否初始化该agent!", true, function (val) {
            if (!val) {
                return;
            }
            var str = '';
            var url = 'http://' + agent.ip + ':5000/api/v1/apps/init';
            if (agent.desc != null) {
                angular.forEach(uCloud_zones, function (zones) {
                    if (agent.desc.indexOf(zones.zone_title) > -1) {
                        str += zones.zone_code + ','
                    }
                });
                str = str.substr(0, str.length - 1);
                url = url + '?zone_codes=' + str;
            }
            $http.get(url).success(function (data) {
                if (data.success == true) {
                    openDialogAlert(ngDialog, $scope, "调用agent成功,请稍后查看应用启动状态!");
                } else {
                    alert(data.msg);
                }
            })
        })
    };

    //按区域初始化启动应用
    $scope.initZoneApp = function (agent) {
        openDialog(ngDialog, $scope, "请确认是否安装该agent的应用!", true, function (val) {
            if (!val) {
                return;
            }
            var url = 'http://' + agent.ip + ':5000/api/v1/apps/installApps';
            doBeetleGet($http, $uibModal, url, function (data) {
                openDialogAlert(ngDialog, $scope, "调用agent成功,请稍后查看应用启动状态!");
            })
        });
    };
    $scope.doAutoTest = function (agent) {
        openDialog(ngDialog, $scope, "请确认执行冒烟测试吗?", true, function (val) {
            if (!val) {
                return;
            }
            var url = 'http://' + agent.ip + ':5000/api/v1/apps/doTest?account=' + getUserAccount();
            doBeetleGet($http, $uibModal, url, function (data) {
                openDialogAlert(ngDialog, $scope, JSON.stringify(data));
                $scope.getAutoStatus(agent);
            });
        });
    };
    $scope.startZoneApp = function (agent) {
        openDialog(ngDialog, $scope, "请确认是否启动该agent的应用!", true, function (val) {
            if (!val) {
                return;
            }
            var url = 'http://' + agent.ip + ':5000/api/v1/apps/startApps';
            doBeetleGet($http, $uibModal, url, function (data) {
                openDialogAlert(ngDialog, $scope, "调用agent成功,请稍后查看应用启动状态!");
            })
        });
    };
    $scope.recoverZoneApp = function (agent) {
        openDialog(ngDialog, $scope, "请确认是否恢复该agent的应用!", true, function (val) {
            if (!val) {
                return;
            }
            var url = 'http://' + agent.ip + ':5000/api/v1/apps/recoverApps';
            doBeetleGet($http, $uibModal, url, function (data) {
                openDialogAlert(ngDialog, $scope, "调用agent成功,请稍后查看应用启动状态!");
            })
        });
    };
    $scope.importDb = function (agent) {
        openDialog(ngDialog, $scope, "请确认是否导入所有区域的数据库!", true, function (val) {
            if (!val) {
                return;
            }
            var url = 'http://' + agent.ip + ':5000/api/v1/zones/install?only_db=false&data_from=demo';

            $.ajax({
                type: "put",
                url: url,
                dataType: "JSON",
                contentType: "application/json",
                async: false,
                success: function (data) {
                    openDialogAlert(ngDialog, $scope, "调用agent成功,请稍后查看应用启动状态!");
                }
            });
        });
    };

    $scope.goinit = function (i) {
        openDialog(ngDialog, $scope, "请确认是否初始化该agent!", true, function (val) {
            if (!val) {
                return;
            }
            $http.get(ucloud_master_url + '/api/v1/agent/init?token_id=' + getTokenId() + '&agent_id=' + i.id).success(function (data) {
                if (data.success == true) {
                    $scope.agent_list();
                } else {
                    alert(data.msg);
                }
            })
        })

    };

    $scope.goToInitPage = function (i) {
        window.location.href = "#/menu/ucInit/" + i.ip;
    };

    $scope.goToProgressPage = function (i) {
        window.location.href = "#/menu/ucProgress/" + i.ip;
    };

    $scope.goucRelease = function (i) {
        window.location.href = "#/menu/newucRelease/" + i.ip + "/" + i.plan_name + "/" + i.id + "/" + i.plan_id;
    };

    $scope.goRelease = function (i) {
        openDialog(ngDialog, $scope, "是否重启agent?", true, function (val) {
            if (!val) {
                return;
            }
            $http.get(ucloud_master_url + '/api/v1/agent/st?token_id=' + getTokenId() + '&agent_id=' + i.id).success(function (data) {
                if (data.success == true) {
                    openDialogAlert(ngDialog, $scope, "重启agent成功");
                } else {
                    openDialogAlert(ngDialog, $scope, data.msg);
                }
            })

        })

    };

    $scope.goupdate_agent = function (i) {

        openDialog(ngDialog, $scope, "确定要申请刷新当前agent吗?", true, function (val) {
            if (!val) {
                return;
            }
            $http.get(ucloud_master_url + '/api/v1/apply_record/update_agent?record_id=' + i.record_id + '&token_id=' + getTokenId()).success(function (data) {
                if (data.success == true) {
                    $scope.agent_list();
                } else {
                    alert(data.msg);
                }
            })
        })

    };
    $scope.cancel_update_agent = function (i) {

        openDialog(ngDialog, $scope, "确定要取消刷新当前agent吗?", true, function (val) {
            if (!val) {
                return;
            }
            $http.get(ucloud_master_url + '/api/v1/apply_record/cancel?record_id=' + i.record_id + '&token_id=' + getTokenId()).success(function (data) {
                if (data.success == true) {
                    $scope.agent_list();
                } else {
                    alert(data.msg);
                }
            })
        })

    };

    $scope.keepAgent = function (i) {
        openDialog(ngDialog, $scope, "确定要申请保留七天么?", true, function (val) {
            if (!val) {
                return;
            }
            $http.get(ucloud_master_url + '/api/v1/apply_record/keep?agent_ip=' + i.ip + '&token_id=' + getTokenId()).success(function (data) {
                if (data.success == true) {
                    $scope.agent_list();
                } else {
                    alert(data.msg);
                }
            })
        })
    };

    $scope.gopostpone = function (i) {
        var info = {};
        info = i;

        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'postpone.html',
            controller: 'postponeCtrl',
            resolve: {
                info: function () {
                    return info;
                }
            }
        });
        modalInstance.result.then(function (result) {
                if (result == 'cancel') {
                    $scope.agent_list();
                }
            },
            function (reason) {
                if (reason == 'cancel') {
                    $scope.agent_list(info);
                }
            });
    };


    $scope.edit = function (i) {
        var info = {};
        info = i;

        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'ucedit.html',
            controller: 'uceditCtrl',
            resolve: {
                info: function () {
                    return info;
                }
            }
        });
        modalInstance.result.then(function (result) {
                if (result == 'cancel') {
                    $scope.agent_list();
                }
            },
            function (reason) {
                if (reason == 'cancel') {
                    $scope.agent_list(info);
                }
            });
    };

    $scope.reload = function () {
        if ($scope.info.agent_ip != '') {
            window.location.href = "#/menu/newucList/";
        } else {
            window.location.reload();
        }
    };

    $scope.showPostponeinfo = function (i) {
        var info = i;
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'postponeinfo.html',
            controller: 'postponeinfoCtrl',
            resolve: {
                info: function () {
                    return info;
                }
            }
        });
    };

    $scope.checkDump = function (vm) {
        if (vm.isRunning) {
            return;
        }
        openDialog(ngDialog, $scope,
            "检查数据库文件状态,将耗费些时间,是否继续?"
            , true, function (flag) {
                if (!flag) {
                    return;
                }
                vm.isRunning = true;
                $http.get(getUCloudAddress(vm.ip) + "/database/check?data_from=demo", {
                    headers: {'Accept': 'application/json'}
                }).success(function (data) {
                    vm.isRunning = false;
                    var name = '';
                    angular.forEach(data, function (dump) {
                        if (dump.dump_status != "文件状态正常") {
                            name += dump.name + ","
                        }
                    });
                    if (name != '') {
                        openDialog(ngDialog, $scope, "存在异常数据库文件," + name, false, function () {
                        });
                    } else {
                        openDialog(ngDialog, $scope, "数据库文件状态全部正常!", false, function () {
                        });
                    }
                }).error(function () {
                    vm.isRunning = false;
                    openDialog(ngDialog, $scope, "请求虚拟机异常,请联系管理员!", false, function () {
                    });
                });
            });
    };

    $scope.updateDumpTime = function (vm) {
        if (vm.isRunning) {
            return;
        }
        openDialog(ngDialog, $scope,
            "是否刷新数据库文件更新时间?"
            , true, function (flag) {
                if (!flag) {
                    return;
                }
                vm.isRunning = true;
                $.ajax({
                    type: "put",
                    url: getUCloudAddress(vm.ip) + '/database/updateDumpTime?data_from=demo',
                    dataType: "JSON",
                    contentType: "application/json",
                    async: false,
                    success: function () {
                        vm.isRunning = false;
                        openDialog(ngDialog, $scope, "刷新数据库文件更新时间完成", false, function () {
                        });
                    },
                    error: function () {
                        vm.isRunning = false;
                        openDialog(ngDialog, $scope, "请求虚拟机异常,请联系管理员!", false, function () {
                        });
                    }
                });
            });
    };
});


myApp.controller('uceditCtrl', function ($scope, $uibModalInstance, info, $http) {
    $scope.info = info;
    // console.log(info);
    $scope.level_list = [];
    $scope.machine_list = [];

    if (info == undefined) {
        $scope.info = [];
        $scope.info.ip = '';
        $scope.info.load_level = '';
        $scope.info.machine_ip = '';
        $scope.istrue = false;
    } else {
        $scope.istrue = true;

    }

    $scope.testIp = function () {
        var testStr = /^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/
        var code = $scope.info.ip;
        if (code.match(testStr)) {
            $scope.info.ipLock = false;
            $scope.info.codeMsg = '';
        } else {
            $scope.info.ipLock = true;
            $scope.info.codeMsg = '请输入正确的ip地址!'
        }
    }


    $http.get(ucloud_master_url + '/api/v1/load_level/?token_id=' + getTokenId()).success(function (data) {
        $scope.level_list = data.data;
    });


    $http.get(ucloud_master_url + '/api/v1/machine/?token_id=' + getTokenId()).success(function (data) {
        $scope.machine_list = data.data;
    });


    $scope.save = function () {
        if ($scope.info.id == undefined) {
            if ($scope.info.ip == '') {
                alert('请输入agent_ip!');
                return false;
            }
            if ($scope.info.load_level == '') {
                alert('请选择负载级别！');
                return false;
            }
            if ($scope.info.machine_ip == '') {
                alert('请选择machine_ip');
                return false;
            }
            if ($scope.info.vm_id == '') {
                alert('请填写虚拟机id');
                return false;
            }
            $http.get(ucloud_master_url + '/api/v1/agent/add?ip=' + $scope.info.ip + '&load_level=' + $scope.info.load_level + '&token_id=' + getTokenId() + '&machine_ip=' + $scope.info.machine_ip + '&vm_id=' + $scope.info.vm_id).success(function (data) {
                if (data.success == true) {
                    $uibModalInstance.dismiss('cancel');
                } else {
                    alert(data.msg);
                }
            })
        } else {
            $http.get(ucloud_master_url + '/api/v1/agent/update?token_id=' + getTokenId() + '&load_level=' + $scope.info.load_level + '&agent_id=' + $scope.info.id + '&machine_ip=' + $scope.info.machine_ip + '&vm_id=' + $scope.info.vm_id).success(function (data) {
                if (data.success == true) {
                    $uibModalInstance.dismiss('cancel');
                } else {
                    alert(data.msg);
                }
            })
        }

    };

    $scope.cancel = function () {
        // 关闭弹出框
        $uibModalInstance.dismiss('cancel');
    };

});

myApp.controller('postponeCtrl', function ($scope, $uibModalInstance, info, $http, $filter) {
    $scope.info = info;
    $scope.info.postpone_desc = '';
    $scope.info.to_date = new Date($scope.info.expect_recover_date);

    $scope.save = function () {
        $scope.to_date = $filter('date')($scope.info.to_date, "yyyy-MM-dd");
        if ($scope.to_date < info.start_date) {
            alert("回收日期小于开始日期请重新选择");
            return false;
        }
        if ($scope.to_date == info.expect_recover_date) {
            alert("回收时间与修改前相同，请重新修改!");
            return false;
        }
        if ($scope.info.postpone_desc == '') {
            alert('请填写描述!');
            return false;

        }

        $http.get(ucloud_master_url + '/api/v1/postpone_record/apply?agent_ip=' + $scope.info.ip + '&user_id=' + getUserId() + '&plan_name=' + $scope.info.plan_name + '&from_date=' + $scope.info.expect_recover_date + '&apply_id=' + $scope.info.record_id + '&to_date=' + $scope.to_date + '&token_id=' + getTokenId() + '&user_name=' + getUserName() + '&desc=' + $scope.info.postpone_desc).success(function (data) {
            if (data.success == true) {
                $uibModalInstance.dismiss('cancel');
            } else {
                alert(data.msg);
            }
        });

    };


    $scope.cancel = function () {
        // 关闭弹出框
        $uibModalInstance.dismiss('cancel');
    };


});

myApp.controller('postponeinfoCtrl', function ($scope, $uibModalInstance, info, $http) {
    $scope.info = info;
    $scope.info.list = [];
    $http.get(ucloud_master_url + '/api/v1/postpone_record?apply_id=' + $scope.info.record_id + '&token_id=' + getTokenId()).success(function (data) {
        if (data.success == true) {
            $scope.info.list = data.data;
        } else {
            alert(data.msg);
        }
    });
});